package cn.edu.cdut.service;

import cn.edu.cdut.dao.NoticeInfoDao;
import cn.edu.cdut.dto.MyRes;
import cn.edu.cdut.dto.Notice;
import cn.edu.cdut.model.NoticeInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;

/**
 * Author  kobe
 * Created on 2017-06-22-21:31
 */
@Service
public class NoticeInfoService {
        @Autowired
        private NoticeInfoDao noticeInfoDao;

        //获得所有
        @Transactional
        public MyRes getAllNotice() {
                List<NoticeInfo> noticeInfoList = noticeInfoDao.findAll();
                //转换为Json字符串
                ObjectMapper mapper = new ObjectMapper();
                Iterator iter = noticeInfoList.iterator();
                String[] resArr = new String[noticeInfoList.size()];
                int i = 0;
                while(iter.hasNext()){
                        try {
                                resArr[i] = mapper.writeValueAsString(iter.next());
                                i++;
                        } catch (JsonProcessingException e) {
                                e.printStackTrace();
                                return new MyRes(201, "获取公告失败！", null);
                        }
                }
                return new MyRes(200, null, resArr);
        }

        //添加
        @Transactional
        public MyRes addNotice(Notice notice) {
                NoticeInfo noticeInfo = new NoticeInfo();
                noticeInfo.setTitle(notice.getTitle());
                noticeInfo.setContent(notice.getContent());
                noticeInfo.setPublishDate(notice.getPublishDate());
                noticeInfoDao.save(noticeInfo);
                return new MyRes(200, "提交成功！", null);
        }

        //修改
        @Transactional
        public MyRes updateNotice(NoticeInfo noticeInfo) {
                noticeInfoDao.save(noticeInfo);
                return new MyRes(200, "修改成功！", null);
        }

        //单个删除
        @Transactional
        public MyRes removeNotice(long id) {
                noticeInfoDao.delete(id);
                return new MyRes(200, "删除成功！", null);
        }
}
